package com.example.algorithm;

import java.util.LinkedList;

/**
 * 路由表匹配
 *
 * @author
 * @DATE 2024/7/10
 **/
public class IPRouteMatch {

    public static void main(String[] args) {

    }

    // ipTable是个二维数组，每一个数组中第0列存IP，第1列存掩码
    private static String routeSearch(String dstIp, String[][] ipTable) {
        String dstIpBinary = getRoute(dstIp);
        LinkedList<String> maxMatchList = new LinkedList<>();
        int maxMatch = -1;
        for (String[] strings : ipTable) {
            String tempRoute = strings[0];
            int maxNum = Integer.parseInt(strings[1]);
            // 0.0.0.0/0匹配任意目的IP
            if (tempRoute.equals("0.0.0.0") && maxNum == 0) {
                maxMatch = maxNum;
                maxMatchList.add(tempRoute + "/" + maxNum);
                continue;
            }
            // 匹配且当前掩码m大于临时保存的maxMatch
            if (isMatch(dstIpBinary, getRoute(tempRoute), maxNum) && maxNum > maxMatch) {
                maxMatchList.clear();
                maxMatch = maxNum;
                maxMatchList.add(tempRoute + "/" + maxNum);
            }
        }

        if (maxMatchList.isEmpty()) {
            return "empty";
        }
        return maxMatchList.getFirst();
    }

    // 判断在给定matchNum长度下，是否匹配
    private static boolean isMatch(String src, String ds, int matchNum) {
        for (int i = 0; i < matchNum; i++) {
            if (src.charAt(i) != ds.charAt(i)) {
                return false;
            }
        }
        return true;
    }

    // 将IP地址转换成二进制
    private static String getRoute(String s) {
        String[] ipSplit = s.split("\\.");
        StringBuilder stringBuilder = new StringBuilder();
        for (String ip : ipSplit) {
            // 转换成二进制，不足8位，则补0
            String binaryString = Integer.toBinaryString(Integer.parseInt(ip));
            String formatBinaryStr = String.format("%8s", binaryString);
            formatBinaryStr = formatBinaryStr.replace(" ", "0");
            stringBuilder.append(formatBinaryStr);
        }
        return stringBuilder.toString();
    }
}
